package com.lms.netty.rpc.consumer;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.concurrent.Callable;

/**
 * @Author: 李孟帅
 * @CreateTime: 2020-06-19 17:31
 * @Description:
 */
public class RpcNettyClientHandler extends ChannelInboundHandlerAdapter implements Callable {
    private ChannelHandlerContext context;
    private String result;
    private String param;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channelActive 通道就绪");
        context = ctx;
//        context.writeAndFlush("========");
    }

    @Override
    public synchronized void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("channelRead：当前线程："+Thread.currentThread().getName());
        System.out.println("channelRead 读取消息");
        result = msg.toString();
        notify();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println(cause.getMessage());
        ctx.close();
    }

    @Override
    public synchronized Object call() throws Exception {
        System.out.println("call:当前线程："+Thread.currentThread().getName());
        System.out.println("call 发送消息 ，，，");
        context.writeAndFlush(param);
        wait();
        System.out.println("call 接受消息 ，，，");
        return result;
    }

    public void setParam(String param) {
        this.param = param;

    }
}
